<%
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 版权所有（C）2018 viviworld
' 本程序为自由软件，在自由软件联盟发布的GNU通用公共许可协议的约束下，你可以对其进行再发布及修改。协议版本为第三版或（随你）更新的版本。
' 我们希望发布的这款程序有用，但不保证，甚至不保证它有经济价值和适合特定用途。详情参见GNU通用公共许可协议。
' 你理当已收到一份GNU通用公共许可协议的副本，如果没有，请查阅<http://www.gnu.org/licenses/>

' QQ: 548841861 （木鱼）
' Email： 365zph@gmail.com
' 项目地址：https://gitee.com/banrenma/RefineCMS
' 协议地址： https://gitee.com/banrenma/RefineCMS/blob/master/LICENSE
' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

%>
<% If Not DIRECT_VISIT Then Response.Write "No direct script access allowed" : Response.End%>
<%
Class cls_Admin
    Public iID, sUsername, sPassword, iRole, iStatus, dCreatedAt, sCreatedIp, sLastIP, dLastTime, iHits
    Private iPageSize, iAbsolutePage, iPageCount
    Private p_current_login_ip
    Private Sub Class_Initialize
        ' on error resume next
        p_current_login_ip = "rf_admin_login_count" & rfUserIP() & Date()
        iID = 0
        sUsername = ""
        sPassword = ""
        iRole = 0
        iStatus = 0
        dCreatedAt = ""
        sCreatedIp = ""
        sLastIP = ""
        dLastTime = ""
        iHits = 0
        iPageSize = 1000
        iAbsolutePage = 1
    End Sub

    Private Sub class_terminate
    End Sub

    Property Get PageCount()
        PageCount = iPageCount
    End Property

    Property Let PageSize(param_pageSize)
        iPageSize = param_pageSize
    End Property

    Property Get AbsolutePage()
        AbsolutePage = iAbsolutePage
    End Property

    Property Let AbsolutePage(param_absolutePage)
        iAbsolutePage = param_absolutePage
    End Property

    Private Function validateUsername()
        validateUsername = False
        Dim pattern, regEx
        pattern = "^[a-zA-Z][a-zA-Z0-9_]{5,31}$"
        Set regEx = New RegExp
        regEx.Pattern = pattern
        regEx.IgnoreCase = True
        regEx.Global = True
        If regEx.Test(sUsername) Then
            validateUsername = True
        End If
        Set regEx = Nothing
    End Function

    Private Function usernameExists
        usernameExists = False
        Dim rs, sql
        sql = "SELECT id FROM `users` WHERE username='" & rfCleanSingleQuotation(sUsername) & "'"
        rfStartWatch()
        Set rs = g_conn.Execute(sql)
        rfEndWatchWithDB(sql)
        If Not rs.EOF Then
            If rs(0) <> iID Then
                usernameExists = True
            End If    
        End If
    End Function

    Public Sub init(id)
        Dim rs, sql
        Set rs=Server.CreateObject("ADODB.recordset")
        sql = "SELECT * FROM `users` WHERE id=" & id
        rfStartWatch()
        rfEndWatchWithDB(sql)
        rs.Open sql, g_conn, 1, 1
        If Not rs.EOF Then
            iID = id
            sUsername = rs("username")
            iRole = rs("role")
            iStatus = rs("status")
            dCreatedAt = rs("created_at")
            sCreatedIp = rs("created_ip")
            dLastTime = rs("last_time")
            sLastIP = rs("last_ip")
            iHits = rs("hits")
        End If
        rs.Close
        Set rs = Nothing
    End Sub

    Public Function save()
        If Not validateUsername() Then
            save = T("rf_lang_login_user_validate")
            Exit Function
        End If
        If usernameExists Then
            save = T("rf_lang_login_user_exists")
            Exit Function
        End If
        Dim rs, sql
        Set rs = Server.CreateObject("ADODB.recordset")
        rfStartWatch()
        If iID > 0 Then
            sql = "SELECT * FROM users WHERE id=" & rfConvertInt(iID)
            rs.Open sql, g_conn, 1, 3
        Else
            sql = "SELECT * FROM users WHERE 1=2"
            rs.Open sql, g_conn, 1, 3
            rs.AddNew
        End If
        rfEndWatchWithDB(sql)
        rs("username") = sUsername
        rs("role") = iRole
        rs("status") = iStatus
        If rfIsEmpty(rs("salt")) Then
            rs("salt") = rfGenerateHash
        End If
        rs("password") = SHA256(sPassword & "_" & rs("salt"))
        If rfIsEmpty(rs("created_at")) Then
            rs("created_at") = Now()
        End If
        If rfIsEmpty(rs("created_ip")) Then
            rs("created_ip") = rfUserIP()
        End If
        rfStartWatch()
        rs.Update
        rfEndWatchWithDB("ADO: table.admins:update-save()")
        save = True
        rs.Close
        Set rs = Nothing
    End Function

    Public Function list()
        list = null
        Dim rs, sql
        Set rs=Server.CreateObject("ADODB.recordset")
        sql = "SELECT * FROM `users` ORDER BY ID DESC"
        rfStartWatch()
        rs.Open sql, g_conn, 1, 1
        rfEndWatchWithDB(sql)
        rs.PageSize = iPageSize
        rs.AbsolutePage = fmtPaginationAbsolutePage(iAbsolutePage, rs.PageCount)
        iPageCount = rs.PageCount
        iAbsolutePage = rs.AbsolutePage
        list = rs.GetRows(rs.PageSize)
        rs.Close
        Set rs = Nothing
    End Function

    Public Function login()
        If checkTooManyLoginCount() Then
            login = T("rf_lang_login_too_many_count")
            Exit Function
        End If
        sUsername   = rfCleanInput(trim(Request.Form ("username")))
        sPassword   = trim(Request.Form ("password"))
        Dim rs, sql
        Set rs=Server.CreateObject("ADODB.recordset")
        sql = "SELECT * FROM `users` WHERE username='" & sUsername & "'"
        rfStartWatch()
        rs.Open sql, g_conn, 1, 3
        rfEndWatchWithDB(sql)
        If rs.EOF Then
            login = T("rf_lang_login_username_password_dismatch")
        Else
            If rs("password") <> SHA256(sPassword & "_" & rs("salt")) Then
                login = T("rf_lang_login_username_password_dismatch")
            ElseIf rs("status") = 2 Then
                login = T("rf_lang_login_the_user_is_forbidden")
            ElseIf rs("status") = 3 Then
                login = T("rf_lang_login_the_user_is_deleted")
            Else
                rs("last_time") = Now()
                rs("last_ip") = rfUserIP()
                rs("hits") = rs("hits") + 1
                rfStartWatch()
                rs.Update
                rfEndWatchWithDB("ADO: table.admins:update-login()")
                Session("rf_user_id") = rs("id")
                Session("rf_user_username") = rs("username")
                Session("rf_user_role") = rs("role")
                Session("rf_user_last_time") = rs("last_time")
                Session("rf_user_last_ip") = rs("last_ip")
                login = True
            End If
        End If
        rs.Close
        Set rs = Nothing
    End Function

    Public Sub del
        Dim sql
        sql = "DELETE FROM `users` WHERE id=" & rfConvertInt(iID)
        rfStartWatch()
        g_conn.Execute(sql)
        rfEndWatchWithDB(sql)
    End Sub

    Private Function checkTooManyLoginCount
        checkTooManyLoginCount = False
        If rfIsEmpty( Application(p_current_login_ip) ) Then
            Application(p_current_login_ip) = 1
        End If
        Application(p_current_login_ip) = Application(p_current_login_ip) + 1
        If Application(p_current_login_ip) > RF_TODAY_ADMIN_LOGIN_COUNT Then
            checkTooManyLoginCount = True
        End If
    End Function

End Class

%>